package com.gulimall.ware.listener;

import com.gulimall.common.constrant.WareConstant;
import com.gulimall.common.to.rabbit.WareLockTo;
import com.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author kkk
 * @date 2022/8/6
 */
@RabbitListener(queues = WareConstant.WARE_STOCK_RELEASE_QUEUE)
@Component
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handlerStockLockedRelease(WareLockTo wareLockTo, Channel channel, Message message) throws IOException {
        try {
            wareSkuService.unLockStock(wareLockTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void handlerCloseOrder(String orderSn, Channel channel, Message message) throws IOException {
        try {
            wareSkuService.closeOrder(orderSn);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
